//
//  ViewController.m
//  myhuibao
//
//  Created by lijun on 13-2-4.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//
#import "HomeViewController.h"
//#import "HouseViewController.h"
#import "RestaurantSearchViewController.h"
#import "NearSearchViewController.h"
#import "HotSearchViewController.h"
#import "LatestViewController.h"
#import "PromotionSearchViewController.h"
#import "MainTabViewController.h"
#import "SBJson.h"
#import "config.h"
#import "OMGToast.h"
#import<QuartzCore/QuartzCore.h>
#import "CitySelectViewController.h"
#import "TicketCell.h"
#import "TicketDetailViewController.h"
#import "AppDelegate.h"
#import "MobClick.h"
@interface HomeViewController ()

@end

@implementation HomeViewController
@synthesize reqCity;
@synthesize lbCity;
@synthesize lbTips;
@synthesize reqVersion;
@synthesize ischecked;
@synthesize reqAreaHotList;
@synthesize areaView;
//@synthesize navView;
//@synthesize edtKeyword;
- (void)viewDidLoad
{
    [super viewDidLoad];
    originvTicketFrame=_vTicket.frame;
    originlbHotAreaFrame=_lbHotArea.frame;
    originvHotAreaFrame=areaView.frame;
    _vTicket.hidden=YES;
    bRefreshTicket=YES;
	// Do any additional setup after loading the view, typically from a nib.
    [[Config Instance] setLatitude:0];
    [[Config Instance] setLongitude:0];
    [[Config Instance]setLocation:@""];
    [self startUpdates];
    timer=[NSTimer scheduledTimerWithTimeInterval:600
                                           target:self
                                         selector:@selector(startUpdates)
                                         userInfo:nil
                                          repeats:YES];
    cityId = [[Config Instance]getCityId];
    lbCity.text = [[Config Instance]getCity];
    //    [self getCity];
    //[self getAreaHotList];
    if([[Config Instance] getChecked]==false)
        [self doCheck];
    //AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    [self getTicketNotice];
    NSTimer *timerNotice =  [NSTimer scheduledTimerWithTimeInterval:noticeInterval target:self selector:@selector(getTicketNotice) userInfo:nil repeats:YES];
    //[timer fire];
    //    edtKeyword.delegate = self;
    //    _searchView.layer.cornerRadius=3;
    //    _searchView.layer.borderWidth=1;
    //    _searchView.layer.borderColor= TEXTFIELD_COLOR.CGColor;
}


-(void)getTicketNotice
{
    if([[Config Instance] getMemberId]!=0)
    {
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?memberID=%d&password=%@",url_ticketNotice,[[Config Instance] getMemberId],[[Config Instance] getPassword]]];
        ASIHTTPRequest *req = [ASIHTTPRequest requestWithURL:url];
        [req setDidFinishSelector:@selector(finishTicketNotice:)];
        [req setShouldAttemptPersistentConnection:NO];
        [req setDelegate: self];
        [req startAsynchronous];
    }
}

-(void)finishTicketNotice:(ASIHTTPRequest*)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"])
    {
        NSDictionary * data = [dic valueForKey:@"data"];
        if([data[@"isNotice"] intValue]==1)
        {
            MainTabViewController * tab=(MainTabViewController*)[self tabBarController];
            if([tab selectedIndex]!=3)
            {
                UICustomTabBar *item=[[tab customTabBarItems] objectAtIndex:3];
                UIImageView *imageView=(UIImageView*) item.subviews[0];
                imageView.image=[UIImage imageNamed:@"ic_myjlh_bottombar_dot.png"];
                item.tag=1;
            }
            AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
            delegate.bNotice=YES;
        }
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"HomeViewController"];
    // NSLog(@"%d",[self.navigationController.viewControllers count]);
    if (cityId != [[Config Instance]getCityId]) {
        cityId = [[Config Instance]getCityId];
        lbCity.text = [[Config Instance]getCity];
        // bRefreshTicket=YES;
    }
    // if(bRefreshTicket)
    // {
    // bRefreshTicket=NO;
    // }
    _vTicket.frame=originvTicketFrame;
    _lbHotArea.frame=originlbHotAreaFrame;
    areaView.frame=originvHotAreaFrame;
    _vTicket.hidden=YES;
    [self getHotTicket];
    [self getAreaHotList];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"HomeViewController"];
}

-(void)viewDidAppear:(BOOL)animated
{
    
    // NSLog(@"%d",[self.navigationController.viewControllers count]);
}
- (void)viewDidUnload
{
    [self setLbCity:nil];
    [self setLbTips:nil];
    [self setSvMain:nil];
    [self setAreaView:nil];
    //    [self setNavView:nil];
    //   [self setEdtKeyword:nil];
    //    [self setSearchView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title=@"主页";
        
    }
    return self;
}
- (void) getCity{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_city];
    reqCity = [ASIHTTPRequest requestWithURL:url];
    [reqCity setShouldAttemptPersistentConnection:NO];
    [reqCity setDidFinishSelector:@selector(finishCity:)];
    isCityFinished = false;
    [reqCity setDelegate: self];
    [reqCity startAsynchronous];
}

- (void)finishCity:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    arrayCity = [dic valueForKey:@"data"];
    isCityFinished = true;
    //    NSLog(@"%@",arrayCity);
    
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
    isCityFinished = true;
    isCheckFinished = true;
    isAreaHotListFinished = true;
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
    }
}
- (IBAction)showPromotion:(id)sender {
    PromotionSearchViewController *view = [[PromotionSearchViewController alloc] initWithNibName:@"PromotionSearchViewController" bundle:nil] ;
    view.hidesBottomBarWhenPushed=YES;
    [[ self navigationController] pushViewController:view animated:YES];
    //    [view release];
}

- (IBAction)showHouse:(id)sender {
    //    HouseViewController *view = [[HouseViewController alloc] initWithNibName:@"HouseViewController" bundle:nil] ;
    //    view.showback = 1;
    //    [[ self navigationController] pushViewController:view animated:YES];
    //    [view release];
    MainTabViewController *mainTabViewController;
    mainTabViewController = [[MainTabViewController alloc] init];
    [mainTabViewController selectViewController:2];
    [self.view.window addSubview:mainTabViewController.view];
    
}

- (IBAction)showRestaurant:(id)sender {
    //    RestaurantViewController *view = [[[RestaurantViewController alloc] initWithNibName:@"RestaurantViewController" bundle:nil] autorelease] ;
    //    view.showback = 1;
    //    [[ self navigationController] pushViewController:view animated:YES];
    //
    MainTabViewController *mainTabViewController;
    mainTabViewController = [[MainTabViewController alloc] init];
    [mainTabViewController selectViewController:1];
    [self.view.window addSubview:mainTabViewController.view];
    
    //    [view release];
}

- (IBAction)showHot:(id)sender {
    HotSearchViewController *view = [[HotSearchViewController alloc] initWithNibName:@"HotSearchViewController" bundle:nil] ;
    view.hidesBottomBarWhenPushed=YES;
    view.iHotType=HOTHOT;
    [[ self navigationController] pushViewController:view animated:YES];
    
}

- (IBAction)showLatest:(id)sender {
    LatestViewController *view = [[LatestViewController alloc] initWithNibName:@"LatestViewController" bundle:nil] ;
    view.hidesBottomBarWhenPushed=YES;
    [[ self navigationController] pushViewController:view animated:YES];
}

- (IBAction)showCity:(id)sender {
    //    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择城市..." options:arrayCity fullHeight:72 ];
    //    lplv.name = @"cityName";
    //    lplv.delegate = self;
    //    [lplv showInView:self.view animated:YES];
    //    [lplv release];
    CitySelectViewController *view = [[CitySelectViewController alloc] initWithNibName:@"CitySelectViewController" bundle:nil] ;
    //    view.arrayCity = arrayCity;
    view.hidesBottomBarWhenPushed=YES;
    [[ self navigationController] pushViewController:view animated:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    [theTextField resignFirstResponder];
    return YES;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    //    _searchView.layer.borderColor= TEXTFIELD_HOTCOLOR.CGColor;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    //   _searchView.layer.borderColor= TEXTFIELD_COLOR.CGColor;
}

- (IBAction)doKeywordSearch:(id)sender {
    //    NSString *keyword = [edtKeyword.text copy];
    //    keyword = [[keyword stringByReplacingOccurrencesOfString:@" " withString:@""] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //    if ([keyword isEqualToString:@""]) {
    ////        [OMGToast showWithText:@"请输入商户名或地址"bottomOffset:100 duration:3];
    //        [self showHot:self];
    //    }else{
    //        RestaurantSearchViewController  *view = [[RestaurantSearchViewController alloc] initWithNibName:@"RestaurantSearchViewController" bundle:nil];
    //        view.cityId = 0;
    //        view.areaId = 0;
    //        view.cuisineId = 0;
    //        view.discoutId = 0;
    //        view.reviewId = 0;
    //        view.keyword = keyword;
    //        view.merchantType=1;
    //        view.hidesBottomBarWhenPushed=YES;
    //        [[self navigationController] pushViewController:view animated:YES];
    //    }
}

- (IBAction)doPhone:(id)sender {
    //    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://4000509177"]];
    //    NSLog(@"%@",@"4000509177");
    NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",CALL_NUMBER]];
    if ( !phoneCallWebView ) {
        phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
    }
    [phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
}

- (IBAction)showRecommand:(id)sender {
    HotSearchViewController *view = [[HotSearchViewController alloc] initWithNibName:@"HotSearchViewController" bundle:nil] ;
    view.hidesBottomBarWhenPushed=YES;
    view.iHotType=HOTRECOMMAND;
    [[ self navigationController] pushViewController:view animated:YES];
}

- (IBAction)showCard:(id)sender {
    HotSearchViewController *view = [[HotSearchViewController alloc] initWithNibName:@"HotSearchViewController" bundle:nil] ;
    view.hidesBottomBarWhenPushed=YES;
    view.iHotType=HOTCARD;
    [[ self navigationController] pushViewController:view animated:YES];
    
}

- (IBAction)ShowMoreTicket:(id)sender {
    HotSearchViewController *view = [[HotSearchViewController alloc] initWithNibName:@"HotSearchViewController" bundle:nil] ;
    view.hidesBottomBarWhenPushed=YES;
    view.iHotType=HOTTICKET;
    [[ self navigationController] pushViewController:view animated:YES];
    
}

- (IBAction)showNear:(id)sender {
    NearSearchViewController *view = [[NearSearchViewController alloc] initWithNibName:@"NearSearchViewController" bundle:nil] ;
    view.hidesBottomBarWhenPushed=YES;
    int id=((UIButton*)sender).tag;
    if(id==1)
    {
        view.iNearType=NEARFOOD;
    }
    else if(id==2)
    {
        view.iNearType=NEARKTV;
    }
    else if(id==3)
    {
        view.iNearType=NEARTEA;
    }
    else if(id==4)
    {
        view.iNearType=NEARTICKET;
    }
    [[ self navigationController] pushViewController:view animated:YES];
}


- (void)startUpdates
{
    // Create the location manager if this object does not
    // already have one.
    //    if (nil == locationManager)
    //        locationManager = [[CLLocationManager alloc] init];
    //
    //    locationManager.delegate = self;
    //    locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
    //
    //    // Set a movement threshold for new events
    //    locationManager.distanceFilter = 500;
    //
    //    [locationManager startUpdatingLocation];
    locationManager = [[CLLocationManager alloc] init];//创建位置管理器
    locationManager.delegate=self;
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    locationManager.distanceFilter=500.0f;
    //启动位置更新
    [locationManager startUpdatingLocation];
    
}


// Delegate method from the CLLocationManagerDelegate protocol.
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    // If it's a relatively recent event, turn off updates to save power
    NSDate* eventDate = newLocation.timestamp;
    NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
    if (abs(howRecent) < 5.0)
    {
        [manager stopUpdatingLocation];
        
        printf("latitude %+.6f, longitude %+.6f\n",
               newLocation.coordinate.latitude,
               newLocation.coordinate.longitude);
        MKReverseGeocoder *reverseGeocoder =[[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
        //        NSLog(@"%g",newLocation.coordinate.latitude);
        //        NSLog(@"%g",newLocation.coordinate.longitude);
        //        NSLog(@"%g",newLocation.horizontalAccuracy);
        [[Config Instance] setLatitude:newLocation.coordinate.latitude];
        [[Config Instance] setLongitude:newLocation.coordinate.longitude];
        reverseGeocoder.delegate = self;
        [reverseGeocoder start];
        
    }
    // else skip the event and process the next one.
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error{
    NSLog(@"MKReverseGeocoder has failed.");
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark{
    [[Config Instance] setLocation:placemark.title];
    //    NSLog(@"当前地理信息为：%@",placemark);
    //    NSLog(@"%@",placemark.locality);
    [[Config Instance]setLocateCity:placemark.locality];
    if([placemark.locality isEqualToString:[[Config Instance]getCity]]
       ||[placemark.locality isEqualToString:[NSString stringWithFormat:@"%@市",[[Config Instance]getCity] ]]){
        lbTips.hidden = true;
    }else{
        //        lbTips.text = [NSString stringWithFormat:@"定位到%@，请切换城市。",placemark.locality];
        //        lbTips.hidden = false;
        [OMGToast showWithText:[NSString stringWithFormat:@"定位到%@，请切换城市。",placemark.locality] bottomOffset:100 duration:10];
        
    }
}
#pragma mark - LeveyPopListView delegates
- (void)leveyPopListView:(LeveyPopListView *)popListView didSelectedIndex:(NSInteger)anIndex
{
    lbCity.text = [NSString stringWithFormat:@"%@",[[arrayCity objectAtIndex:anIndex] objectForKey:@"cityName"]];
    cityId = [[[arrayCity objectAtIndex:anIndex] objectForKey:@"cityID"] intValue];
    [[Config Instance] setCityId:cityId];
    [[Config Instance]setCity:lbCity.text];
    lbTips.hidden = true;
    
}
- (void)leveyPopListViewDidCancel
{
    //edtCity.text = @"You have cancelled";
}
#pragma mark - LeveyPopListView delegates
- (void)leveyPopListView:(LeveyPopListView *)popListView didSelectedIndex:(NSInteger)anIndex options:(NSArray *)_options didSelectedTypeIndex:(NSInteger)anTypeIndex
{
}
- (void)doCheck {
    NSURL *url = [NSURL URLWithString:url_lastVersion];
    isCheckFinished = false;
    reqVersion=[ASIFormDataRequest requestWithURL:url];
    [reqVersion setPostValue:@"iPhone" forKey:@"clientType"];
    [reqVersion setPostValue:curversion forKey:@"clientVersion"];
    
    [reqVersion setDidFinishSelector:@selector(finishCheck:)];
    [reqVersion setShouldAttemptPersistentConnection:NO];
    [reqVersion setDelegate: self];
    [reqVersion startAsynchronous];
}
-(void)finishCheck:(ASIHTTPRequest*) request{
    isCheckFinished = true;
    [[Config Instance] setChecked:true];
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    //NSLog(@"%@",dic);
    NSDictionary *data = [dic valueForKey:@"data"];
    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"])
    {
        float ver = [[data valueForKey:@"clientVersion"] floatValue];
        if(ver > [curversion floatValue]){
            downloadURL = [data valueForKey:@"downloadURL"];
            NSString *msg = [data valueForKey:@"clientDescription"];
            if ( [data valueForKey:@"clientDescription"]==[NSNull null]) {
                msg=@"";
            }
            UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@""
                                                          message:msg
                                                         delegate:self
                                                cancelButtonTitle:@"取消"
                                                otherButtonTitles:@"下载",nil];
            for(UIView *view in alert.subviews)
            {
                if([[view class] isSubclassOfClass:[UILabel class]])
                {
                    ((UILabel*)view).textAlignment=NSTextAlignmentLeft;
                }
            }
            [alert show];
        }
        //        else{
        //            UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
        //                                                          message:@"您的客户端不需要更新"                                                         delegate:nil
        //                                                cancelButtonTitle:@"取消"
        //                                                otherButtonTitles:nil];
        //            [alert show];
        //            [alert release];
        //
        //        }
    }
    //    else{
    //        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
    //                                                      message:[dic valueForKey:@"log"]                                                         delegate:nil
    //                                            cancelButtonTitle:@"取消"
    //                                            otherButtonTitles:nil];
    //        [alert show];
    //        [alert release];
    //    }
    if([self.navigationController.viewControllers count]==0)
    {
        [self.navigationController addChildViewController:self];
    }
}
-(void) viewDidDisappear:(BOOL)animated{
    //    [OMGToast showWithText:@"关闭。。。"];
    if(!isCityFinished){
        [reqCity clearDelegatesAndCancel];
        [reqCity cancel];
        isCityFinished = true;
    }if(!isCheckFinished){
        [reqVersion clearDelegatesAndCancel];
        [reqVersion cancel];
        isCheckFinished=true;
    }
}
//定义的委托，buttonindex就是按下的按钮的index值
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex==1){
        NSURL *url = [NSURL URLWithString:url_download];
        if (![[UIApplication sharedApplication] openURL:url])
            NSLog(@"%@%@",@"Failed to open url:",[url description]);
    }
}

- (void)dealloc {
    phoneCallWebView = nil;
}

- (void)getAreaHotList {
    
    NSURL *url = [NSURL URLWithString:url_areaHotList];
    isAreaHotListFinished = false;
    reqAreaHotList=[ASIFormDataRequest requestWithURL:url];
    [reqAreaHotList setPostValue:[NSString stringWithFormat:@"%d",cityId] forKey:@"cityID"];
    [reqAreaHotList setDidFinishSelector:@selector(finishAreaHotList:)];
    [reqAreaHotList setShouldAttemptPersistentConnection:NO];
    [reqAreaHotList setDelegate: self];
    [reqAreaHotList startAsynchronous];
}
- (void)finishAreaHotList:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    arrayAreaHotList = [dic valueForKey:@"data"];
    isAreaHotListFinished = true;
    [tagList removeFromSuperview];//clear lasted uilables
    tagList = [[DWTagList alloc] initWithFrame:CGRectMake(16.0f, 0.0f, 295.0f, 110.0f)];
    //NSArray *array = [[NSArray alloc] initWithObjects:@"Foo", @"Tag Label 1", @"Tag Label 2", @"Tag Label 3", @"Tag Label 4", @"Tag Label 5", nil];
    if(arrayAreaHotList!=nil)
        [tagList setTags:arrayAreaHotList];
    //    [self.view addSubview:tagList];
    [areaView addSubview:tagList];
    areaView.frame = CGRectMake(0,areaView.frame.origin.y,320,tagList.fittedSize.height);
    // navView.frame = CGRectMake(0,areaView.frame.origin.y+ tagList.fittedSize.height+5,320,190);
    _svMain.delegate = self;
    [_svMain setContentSize:CGSizeMake(320, 230+tagList.fittedSize.height+(_vTicket.hidden?0:_vTicket.frame.size.height))];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [tableDataArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 302;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"TicketCellIdentifier";
    TicketCell *cell = (TicketCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"TicketCell" owner:nil options:nil];
        cell = [array objectAtIndex:0];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    cell.contentView.backgroundColor=[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
    if([item[@"merchantTypeID"] intValue]==1 )
    {
        cell.ImageType.image=[UIImage imageNamed:@"icon_food.png"];
    }
    else if([item[@"merchantTypeID"] intValue]==2)
    {
        cell.ImageType.image=[UIImage imageNamed:@"icon_ktv.png"];
    }
    else if ([item[@"merchantTypeID"] intValue]==3)
    {
        cell.ImageType.image=[UIImage imageNamed:@"icon_tea.png"];
    }
    cell.lbName.text=item[@"merchantName"];
    cell.lbTitle.text=item[@"title"];
    cell.lbCount.text=[NSString stringWithFormat:@"下载次数:%d",[item[@"downloadNum"] intValue]];
    NSString *endTime=item[@"endDate"];
    cell.lbTime.text=[NSString stringWithFormat:@"有效期：%@",endTime];
    int dis=item[@"distance"]==[NSNull null]?100000:[item[@"distance"] intValue];
    if(dis<1000)
    {
        cell.lbDistance.text=[NSString stringWithFormat:@"%dm",dis];
    }else if(dis>=1000 && dis<=50000)
    {
        cell.lbDistance.text=[NSString stringWithFormat:@"%.1fkm",dis*1.0/1000];
    }
    else
    {
        cell.lbDistance.text=@"";
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    TicketDetailViewController *view=[[TicketDetailViewController alloc] initWithNibName:@"TicketDetailViewController" bundle:nil];
    view.hidesBottomBarWhenPushed=YES;
    view.merchantTypeID=[[item objectForKey:@"merchantTypeID"] intValue];
    view.couponID=[[item objectForKey:@"couponID"] intValue];
    [self.navigationController pushViewController:view animated:YES];
}

-(void)getHotTicket
{
    // NSLog(@"%@&cityID=%d&longitude=%f&latitude=%f",url_homeHotTicketList,cityId,[[Config Instance] getLongitude],[[Config Instance] getLatitude]);
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@&cityID=%d&longitude=%f&latitude=%f",url_homeHotTicketList,cityId,[[Config Instance] getLongitude],[[Config Instance] getLatitude]] ];
    ASIHTTPRequest *req = [ASIHTTPRequest requestWithURL:url];
    [req setShouldAttemptPersistentConnection:NO];
    [req setDelegate: self];
    [req setDidFinishSelector:@selector(finishHotTicket:)];
    [req startAsynchronous];
}

- (void)finishHotTicket:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    tableDataArray = [dic valueForKey:@"data"];
    _vTicket.hidden=NO;
    if((NSNull*)tableDataArray==[NSNull null])
    {
        return;
    }
    if([tableDataArray count]==1)
    {
        CGRect rect=_vTicket.frame;
        rect.size.height-=70;
        [_vTicket setFrame:rect];
        rect=_lbHotArea.frame;
        rect.origin.y-=70;
        [_lbHotArea setFrame:rect];
        rect=areaView.frame;
        rect.origin.y-=70;
        [areaView setFrame:rect];
    }
    else if([tableDataArray count]==0)
    {
        CGRect rect=_vTicket.frame;
        rect.size.height=0;
        [_vTicket setFrame:rect];
        _vTicket.hidden=YES;
        rect=_lbHotArea.frame;
        rect.origin.y-=160;
        [_lbHotArea setFrame:rect];
        rect=areaView.frame;
        rect.origin.y-=160;
        [areaView setFrame:rect];
    }
    [_TicketTable reloadData];
    [Config setExtraCellLineHidden:_TicketTable];
}
@end
